<?php
namespace app\api\command;

/**
 * 讯飞在线语音合成
 */
class Tts
{
    /**
     * 拼接签名
     * @param $api_key
     * @param $api_secret
     * @param $time
     * @return string
     */
    public function sign($api_key, $api_secret, $time)
    {
        $signature_origin = 'host: tts-api.xfyun.cn' . "\n";
        $signature_origin .= 'date: ' . $time . "\n";
        $signature_origin .= 'GET /v2/tts HTTP/1.1';
        $signature_sha = hash_hmac('sha256', $signature_origin, $api_secret, true);
        $signature_sha = base64_encode($signature_sha);
        $authorization_origin = 'api_key="' . $api_key . '", algorithm="hmac-sha256", ';
        $authorization_origin .= 'headers="host date request-line", signature="' . $signature_sha . '"';
        $authorization = base64_encode($authorization_origin);
        return $authorization;
    }

    /**
     * 生成接口鉴权Url
     * @param $api_key
     * @param $api_secret
     * @return string
     */
    public function createAuthUrl($api_key, $api_secret)
    {
        $url = 'wss://tts-api.xfyun.cn/v2/tts';
        $time = date('D, d M Y H:i:s', strtotime('-8 hour')) . ' GMT';
//        $time = date('D, d M Y H:i:s', time()) . ' GMT';
//         print_r($time);
//         exit;
        $authorization = $this->sign($api_key, $api_secret, $time);
        $url .= '?' . 'authorization=' . $authorization . '&date=' . rawurlencode($time) . '&host=tts-api.xfyun.cn';
        return $url;
    }
    /**
     * 生成要发送的消息体
     * @param $app_id 应用ID
     * @param $ent 引擎类型
     * @param $aue 音频编码
     * @param $auf 音频采样率
     * @param $vcn 发音人
     * @param $speed 语速
     * @param $volume 音量
     * @param $pitch 音高
     * @param $bgs 背景音
     * @param $tte 文本编码格式
     * @param $reg 英文发音方式
     * @param $ram 是否读出标点
     * @param $rdn 数字发音方式
     * @param $text 合成文本
     * @return array
     */
    public function createMsg(
        $app_id,
        $text,
        $ent = 'intp65',
        $aue = 'lame', 
        $auf = 'audio/L16;rate=16000', 
        $vcn = 'aisxping', 
        $speed = 50, 
        $volume = 50, 
        $pitch = 50, 
        $bgs = 0,
        $tte = 'UTF8', 
        $reg = '0', 
        $ram = '0', 
        $rdn = '0'
        )
    {
        return [
            'common' => [
                'app_id' => $app_id,
            ],
            'business' => [
                'ent' => $ent,
                'aue' => $aue,
                'sfl' => 1,
                'auf' => $auf,
                'vcn' => $vcn,
                'speed' => (int) $speed,
                'volume' => (int) $volume,
                'pitch' => (int) $pitch,
                'bgs' => (int) $bgs,
                'tte'  => $tte,
                'reg'  => $reg,
                'ram'  => $ram,
                'rdn'  => $rdn,
            ],
            'data' => [
                'status' => 2,
                'text' => base64_encode($text),
            ],
        ];
    }
}
